import os
import uuid

import cv2
import numpy as np
import com.haojiangbo.utils.StrUtils as CharUtils

"""
  
"""


class IdCardReadHander:
    modelPath = ""
    charUtil = None
    tmpSavePath = "/tmp/"

    def __init__(self, modelPath, isDebuger):
        self.modelPath = modelPath
        self.charUtil = CharUtils.CharUtl(self.modelPath, isDebuger=isDebuger)

    def predictByFile(self, tmpFile):
        tmpPath = self.tmpSavePath + str(uuid.uuid1()) + ".jpg"
        tmpFile.save(tmpPath)
        img = cv2.imdecode(np.fromfile(tmpPath, dtype=np.uint8), cv2.IMREAD_GRAYSCALE)
        tmpStr = self.__imgPredict(img)
        os.remove(tmpPath)
        return tmpStr

    # 识别照片
    def predictByImg(self, img, isCoverGary=False):
        if isCoverGary:
            img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        tmpStr = self.__imgPredict(img)
        return tmpStr

    def predictByPath(self, tmpPath):
        img = cv2.imdecode(np.fromfile(tmpPath, dtype=np.uint8), cv2.IMREAD_GRAYSCALE)
        return self.__imgPredict(img)

    def __imgPredict(self, img):
        img = cv2.GaussianBlur(img, (3, 3), 0)
        img = cv2.resize(img, (600, 400))
        # dx = 1 or dy = 1  求偏导数  0代表不求导数， 1代表求1阶导数  也就是斜率  2代表2阶导数  最大为2阶导数
        x = cv2.Sobel(img, cv2.CV_64F, dx=1, dy=0)
        y = cv2.Sobel(img, cv2.CV_64F, dx=0, dy=1)
        x = cv2.convertScaleAbs(x)
        y = cv2.convertScaleAbs(y)
        dst = cv2.addWeighted(x, 0.5, y, 0.5, 0)
        t, binaryImg = cv2.threshold(dst, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
        str = self.charUtil.showImages(binaryImg, img)
        return str
